package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired(required = false)
    private CategoryMapper categoryMapper;


    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetMealMapper setMealMapper;
    /**
     * 添加功能
     * @param category
     */
    @Override
    public void add(Category category) {
        //更改创建时间和修改时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.add(category);
    }

    /**
     * 分页显示功能
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> find(Integer page, Integer pageSize) {
        //设置页面显示条数
        PageHelper.startPage(page,pageSize);
        List<Category> categoryList = categoryMapper.find();
        PageInfo<Category> categoryPageInfo = new PageInfo<>(categoryList);

        Page<Category> categoryPage = new Page<>(categoryPageInfo.getList(), categoryPageInfo.getTotal());
        return categoryPage;
    }

    /**
     * 删除功能
     * @param id
     */
    @Override
    public void delete(Long id) {
        int count = dishMapper.findCount(id);
        if (count>0){
            throw new CustomerException("此菜品里有很多菜,删不了");
        }

        count = setMealMapper.findCount(id);
        if (count>0){
            throw new CustomerException("此菜品关联其他套餐,删不了");
        }

        categoryMapper.delete(id);
    }

    /**
     * 修改功能
     * @param category
     */
    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    /**
     * 查看所有功能
     * @return
     */
    @Override
    public List<Category> find()
    {
        return categoryMapper.find();
    }

    @Override
    public R<List<Category>> list(Integer type) {
        List<Category> categoryList = categoryMapper.list(type);
        return R.success(categoryList);
    }
}
